package ru.spb.osll.myfit.server.parser;

import ru.spb.osll.myfit.common.Content;
import ru.spb.osll.myfit.common.PageElement;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ContentElementParser implements IPageElementParser {
  private final Pattern CONTENT_PATTERN = Pattern.compile("!contents(\\s+\\-R(\\d*))?(\\s+-[gpfh])*\\s*");

  @Override
  public boolean matches(String line) {
    return CONTENT_PATTERN.matcher(line).matches();
  }

  @Override
  public PageElement parse(String line) {
    Integer depth;
    Matcher matcher = CONTENT_PATTERN.matcher(line);
    if (matcher.find()) {
      String level = matcher.group(2);
      String group = matcher.group(1);
      if ((level != null) && (!level.isEmpty()))
        try {
          depth = Integer.parseInt(level);
        } catch (NumberFormatException e) {
          depth = Content.CONTENTS_LEVEL_ALL; //really, this case is not possible
        }
      else if ((group != null) && (!group.isEmpty()))
        depth = Content.CONTENTS_LEVEL_ALL;
      else
        depth = 1;

      return new Content(depth);
    }

    return null;
  }
}
